package com.gitee.limaozhi.nio.example02;

import com.gitee.limaozhi.util.Utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author hzlimaozhi
 * @date 2019/12/20 11:17
 */
public class Server {

    public static void main(String[] args) throws IOException {
        // 1. 创建监听Socket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 2. 设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        // 3. 绑定本地端口
        serverSocketChannel.bind(new InetSocketAddress(8000), 1);
        // 1M缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);

        // 循环处理多个请求
        while (true) {
            // 连接socket
            SocketChannel socketChannel = null;

            // 4. 非阻塞接受连接
            // 没有异步回调，只能同步
            // 无法检查状态，只能重试
            for (int i = 1; i < Integer.MAX_VALUE; i++) {
                socketChannel = serverSocketChannel.accept();
                if (socketChannel == null) {
                    System.out.println("accept等待：" + i);
                    Utils.sleepSeconds(5);
                } else {
                    // 连接socket设置为非阻塞
                    socketChannel.configureBlocking(false);
                    System.out.println("建立连接");
                    break;
                }
            }

            // 5. 读取数据
            for (int i = 1; ; i++) {
                // 缓冲区切换写模式
                buffer.clear();

                int count = socketChannel.read(buffer);
                System.out.println("第" + i + "次读取：" + count);
                if (count < 0) {
                    break;
                } else if (count == 0) {
                    Utils.sleepSeconds(1);
                } else {
                    // 切换读模式
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
//                    System.out.println(new String(bytes));
                }
            }

            // 6. 发送数据
            buffer.clear();
            byte[] bytes = ("OK").getBytes();
            buffer.put(bytes);
            buffer.flip();
            int count = 0;
            while ((count += socketChannel.write(buffer)) < bytes.length) {
                ;
            }
            socketChannel.shutdownOutput();
            socketChannel.close();
        }

//        serverSocketChannel.close();
    }

}
